#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月2日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

from django.http import HttpResponse,HttpResponseNotFound, HttpResponseRedirect   
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson 
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render

from django.contrib.auth.decorators import login_required
from django.contrib import auth
from .forms import LoginForm
redirectUrl = '/'

import logging


def login(request):
    global redirectUrl
    logging.debug( request)
    if request.method == 'GET':
        if 'next' in request.GET:
            redirectUrl = request.GET['next']
        else:
            redirectUrl = '/'
        form = LoginForm()
        return render_to_response('login.html', RequestContext(request, {'form': form,}))
    else:
        form = LoginForm(request.POST)
        
        if form.is_valid():
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                auth.login(request, user)
                #return render_to_response('tools.html', RequestContext(request))
                return HttpResponseRedirect(redirectUrl)
            else:
                return render_to_response('login.html', RequestContext(request, {'form': form,'password_is_wrong':True}))
        else:
            return render_to_response('login.html', RequestContext(request, {'form': form,}))

@login_required
def logout(request):
    auth.logout(request)
    return HttpResponseRedirect("/accounts/login/")
#@login_required
def show_tools(request):
    #print request
     
    return render_to_response('tools.html',{},context_instance=RequestContext(request))


def show_testing(request):
    #print request
     
    return render_to_response('testing2.html',{},context_instance=RequestContext(request))

    